
#include <string>
#include "TaskSyncFully.h"
#include "RequestCheck.h"
#include "ConnectionControl.h"
#include "ConnectionFactory.h"
#include "../client-common/Device.h"
#include "../client-common/Config.h"
#include "../engine/DebugStream.h"

using namespace std;
using namespace Client::Common;

static ConnectionRef CreateDataConnection(string& peer, ConnectionControlRef control_conn) {
	ConnectionRef c = CConnectionFactory::CreateByPeer(peer, control_conn, false);
	if(!c) {
		Engine::DebugStream << "CTaskSyncFile::Exec() - " << "Create connection failed\n";
		return c;
	}
	else {
		try {
			c->Setup();
		}
		catch(std::exception&) {
			c.reset();
		}
	}

	return c;
}

bool CTaskSyncFully::Exec(ConnectionRef conn)
{
	ConnectionControlRef control_conn;
	if(!conn->IsControlConnection()) return false;
	control_conn = boost::dynamic_pointer_cast<CConnectionControl, CConnection>(conn);

	RequestRef request(new CRequestCheck(string("devices")));
	ResponseRef response = conn->SendRequest(request);
	if(!response || response->GetStatus() != RESPONSE_STATUS_OK) return false;

	string content;
	response->GetContentAsString(content);
	
	bool done = true;
	TableRef td = Client::Common::CDevice::GetSerializedTable(content);
	if(td && td->GetCount() > 0) {
		boost::shared_array<RecordRef> recs = td->NextRecords(td->GetCount());
		int count = td->GetCurrentRecordsCount();
		
		for(int i = 0; i < count; i++) {
			DeviceRef dev = boost::dynamic_pointer_cast<Client::Common::CDevice, CRecord>(recs[i]);
			ConnectionRef c = CreateDataConnection(dev->mId, control_conn);
			if(!CTaskFactory::ExecAllFullyTask(dev->mId, c)) done = false;
		}
	}

	if(done) {
		CConfig& conf = CConfig::GetInstance();
		conf.mFullSyncCompleted = true;
		conf.Save();
	}

	return done;
}